package com.itheima.controller;


import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.OrderService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import com.itheima.utils.DateUtils;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private MemberService memberService;
    @Reference
    private SetmealService setmealService;
    @Reference
    private ReportService reportService;

    @RequestMapping("/getMemberReport")
    //用于生成会员数量统计折线图
    public Result getMemberReport(){
        //页面展示折线图所需的数据
        /*
        data:{
            months:['2020.03','2020.04','2020.05'],
            memberCount:[100,200,300]
        }
         */
        //先模拟数据返回试试图表显示
        Map<String,Object> map = new HashMap<>();

        //封装月份的集合，对应着横坐标的data数组
        List<String> monthsList = new ArrayList<>();

        //获取calendar对象，默认为当前时间的日历对象，但是月份 = 实际月份 -1
        Calendar calendar = Calendar.getInstance(); //2020.02


        //查询从当前月往前推12个月的全部数据
        //先将日历指向12月之前的日期
        calendar.add(Calendar.MONTH,-12);  //2019.02

        for (int i = 0; i < 12; i++) {
            //第一次正好补全月份少1的情况
            calendar.add(Calendar.MONTH,1);  //第一次的时候2019.03
            Date date = calendar.getTime();
            monthsList.add(new SimpleDateFormat("yyyy.MM").format(date));
        }
        //此时monthslist中就存放着"2019.03","2019.04"... 共12条数据

        //封装每月的会员数量，对应着series中的data数组
        //从数据库中查询每月累计的会员数
        List<Integer> memberCountList = memberService.findMemberCount(monthsList);

        map.put("months",monthsList);
        map.put("memberCount",memberCountList);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
    }



    @RequestMapping("/getSetmealReport")
    //用于生成套餐预约占比饼形图
    public Result getSetmealReport(){
        //页面用于展示饼形图所需的数据格式：
        /*
        data:{
            setmealNames:['入职检查'，'老年无忧','儿童防疫'],
            setmealCount:[
                {"name":"入职检查","value":200},
                {"name":"老年无忧","value":240},
                {"name":"儿童防疫","value":127},
            ]
        }
        */
        //先模拟数据返回测试
        //数据测试正常后，调用service查询数据库
        //此时发现setmealCount的数据包括了setmealNames中的数据，就可以只查一次数据库
        Map<String,Object> data = new HashMap<>();

        try {
            //因为需要是rpc远程调用，可能由于网络原因出现异常，try/catch
            //调用service方法查询数据库,获取每个套餐的预约数量
            List<Map<String,Object>> setmealCount = setmealService.findSetmealCount();

            //从list中取出所有套餐的名称
            List<String> setmealNames = new ArrayList<>();
            for (Map<String, Object> map : setmealCount) {
                String name = (String) map.get("name");
                setmealNames.add(name);
            }
            //再将前台需要的数据封装到map中
            data.put("setmealNames",setmealNames);
            data.put("setmealCount",setmealCount);

            return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }


    @RequestMapping("/getBusinessReportData")
    //获取运营数据统计表格中的数据
    public Result getBusinessReportData(){
        //前端需要的数据格式
        /*
        {
            reportDate:null,
            todayNewMember :0,
            totalMember :0,
            thisWeekNewMember :0,
            thisMonthNewMember :0,
            todayOrderNumber :0,
            todayVisitsNumber :0,
            thisWeekOrderNumber :0,
            thisWeekVisitsNumber :0,
            thisMonthOrderNumber :0,
            thisMonthVisitsNumber :0,
            hotSetmeal :[
                {name:'阳光爸妈升级肿瘤12项筛查（男女单人）体检套餐',setmeal_count:200,proportion:0.222},
                {name:'阳光爸妈升级肿瘤12项筛查体检套餐',setmeal_count:200,proportion:0.222}
            ]
        }
        */

        //先返回静态数据测试，测试完成后查询数据库
        //此时需要查询的数据库(member表，order表，setmeal和order联合查询)
        try {
            Map<String,Object> map = reportService.getBusinessReportData();
            return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }

    }


    @RequestMapping("/exportBusinessReport")
    //导出运营数据统计
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
        try {
            //首先要获取插叙的数据，然后写入表格中
            //获取查询数据
            Map<String, Object> reportData = reportService.getBusinessReportData();

            //取出查询的结果中的数据
            String reportDate = (String) reportData.get("reportDate");
            Integer todayNewMember = (Integer) reportData.get("todayNewMember");
            Integer totalMember = (Integer) reportData.get("totalMember");
            Integer thisWeekNewMember = (Integer) reportData.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) reportData.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) reportData.get("todayOrderNumber");
            Integer todayVisitsNumber = (Integer) reportData.get("todayVisitsNumber");
            Integer thisWeekOrderNumber = (Integer) reportData.get("thisWeekOrderNumber");
            Integer thisWeekVisitsNumber = (Integer) reportData.get("thisWeekVisitsNumber");
            Integer thisMonthOrderNumber = (Integer) reportData.get("thisMonthOrderNumber");
            Integer thisMonthVisitsNumber = (Integer) reportData.get("thisMonthVisitsNumber");
            List<Map<String,Object>> hotSetmeal = (List<Map<String,Object>>) reportData.get("hotSetmeal");

            /*
            获取模板表格文件的路径
            request.getSession().getServletContext().getRealPath("template")：获取到template文件的真实路径
            File.separator：文件路径的分隔符(自动匹配系统)
            */
            String filePath = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx";
            //创建表格对象(是根据模板文件创建)
            XSSFWorkbook workbook = new XSSFWorkbook(new File(filePath));
            XSSFSheet sheet = workbook.getSheetAt(0);

            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);

            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);
            row.getCell(7).setCellValue(totalMember);

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);
            row.getCell(7).setCellValue(thisMonthNewMember);

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);
            row.getCell(7).setCellValue(todayVisitsNumber);

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);
            row.getCell(7).setCellValue(thisWeekVisitsNumber);

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);
            row.getCell(7).setCellValue(thisMonthVisitsNumber);


            int rowNum = 12;
            for (int i = 0; i < 4; i++) {
                row = sheet.getRow(rowNum+i);
                Map<String, Object> map = hotSetmeal.get(i);
                row.getCell(4).setCellValue((String) map.get("name"));
                row.getCell(5).setCellValue((Long) map.get("setmeal_count"));

                //从数据库中查询的占比是小数，不能直接转化为double，
                BigDecimal proportion = (BigDecimal) map.get("proportion");
                double value = proportion.doubleValue();
                row.getCell(6).setCellValue(value);
            }

            //文件输出
            OutputStream out = response.getOutputStream();
            //告诉浏览器，返回的是什么格式的数据
            response.setContentType("application/vnd.ms-excel");
            //告诉浏览器以附件的形式下载
            response.setHeader("Content-Disposition", "attachment; filename=report.xlsx");
            workbook.write(out);

            out.flush();
            out.close();
            workbook.close();

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }


    @RequestMapping("/exportBusinessReport4PDF")
    //运营数据导出到PDF文件
    public Result exportBusinessReport4PDF(HttpServletRequest request, HttpServletResponse response){
        try {
            //调用service方法，查询出数据
            Map<String, Object> reportData = reportService.getBusinessReportData();

            List<Map<String,Object>> hotSetmeal = (List<Map<String, Object>>) reportData.get("hotSetmeal");


            //获取jrxml的文件真实路径
            String jrxmlPath = request.getSession().getServletContext().getRealPath("template")
                    +File.separator+"health_business3.jrxml";
            String jasperPath = request.getSession().getServletContext().getRealPath("template")
                    +File.separator+"health_business3.jasper";

            //编译模板，生成.jasper文件
            JasperCompileManager.compileReportToFile(jrxmlPath,jasperPath);

            //此处的map是给parameter赋值，list是通过javaBean给fields赋值
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath,
                    reportData,
                    new JRBeanCollectionDataSource(hotSetmeal));



            OutputStream out = response.getOutputStream();
            //告诉浏览器，返回的是什么格式的数据
            response.setContentType("application/pdf");
            //告诉浏览器以附件的形式下载
            response.setHeader("Content-Disposition", "attachment; filename=report.pdf");
            //文件输出
            JasperExportManager.exportReportToPdfStream(jasperPrint,out);

            out.flush();
            out.close();

            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }

    }
}
